package com.kaijie.utils;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Slf4j
public class SignatureUtils {

    public enum SignType {
        MD5, HMACSHA256
    }

    /**
     * 生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
     *
     * @param data    待签名数据
     * @param signKey API密钥
     * @return 签名
     */
    public static String generate(final Map<String, String[]> data, String signKey) {
        Map<String, String> params = new HashMap<>();
        data.forEach((name, values) -> {
            StringBuilder sb = new StringBuilder();
            for (String val : values) {
                if (sb.length() > 0) {
                    sb.append(",").append(val);
                } else {
                    sb.append(val);
                }
            }
            params.put(name, sb.toString());
        });
        return generate(params, signKey, SignType.MD5);
    }

    public static String generate(final Map<String, String> data, String signKey, SignType signType) {
        try {
            Set<String> keySet = data.keySet();
            String[] keyArray = keySet.toArray(new String[keySet.size()]);
            Arrays.sort(keyArray);
            StringBuilder sb = new StringBuilder();
            for (String k : keyArray) {
                if (k.equals("sign")) {
                    continue;
                }
                String value = data.get(k);
//                if (value.length() > 0) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(value).append("&");
            }
            sb.append("key=").append(signKey);
            if (SignType.MD5.equals(signType)) {
                return MD5(sb.toString()).toUpperCase();
            } else if (SignType.HMACSHA256.equals(signType)) {
                return HMACSHA256(sb.toString(), signKey);
            }
        } catch (Exception e) {
            //log.error("生成签名错误： " + e.getMessage());
        }
        return "";
    }

    /**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @return MD5结果
     */
    public static String MD5(String data) throws Exception {
        java.security.MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 生成 HMACSHA256
     *
     * @param data 待处理数据
     * @param key  密钥
     * @return 加密结果
     * @throws Exception
     */
    public static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }
}
